package com.yzf.smsforward.utils;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import com.yzf.smsforward.Constants;
import com.yzf.smsforward.YZFCallback;
import com.yzf.smsforward.manager.LoginManager;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.List;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import static com.yzf.smsforward.Constants.TAG;

/**
 * 项目名称：FoldingVerifyCode
 * 类描述：网络请求工具类
 * 创建人：Administrator
 * 创建时间：2019年10月1日
 */
public class HttpUtils {
    final private int REQUEST_CODE_ASK_PERMISSIONS = 12300;
    private static OkHttpClient mOkHttpClient;
    private static String sessionID = "";
    private static boolean isTest = true;

    public static void doGet(final String url, final YZFCallback callback) {
        mOkHttpClient = getUnsafeOkHttpClient();
        new Thread(new Runnable() {
            @Override
            public void run() {
                Request request = new Request.Builder().url(url).get().build();
                mOkHttpClient.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        callback.onFailed("555", e.getMessage());
                    }

                    @Override
                    public void onResponse(Call call, Response response) {

                        if (response.isSuccessful()) {
                            try {
                                Log.d(TAG, "response.body = " + response.body().string());
                                callback.onSuccess(response.body().string());
                            } catch (IOException e) {
                                callback.onFailed(String.valueOf(response.code()), e.getMessage());
                                e.printStackTrace();
                            }

                        } else {
                            callback.onFailed(String.valueOf(response.code()), response.message());
                            Log.d(TAG, "response.message = " + response.message());
                        }
                    }
                });
            }
        }).start();
    }

    public static String doGetOutIp() {

        if (!TextUtils.isEmpty(com.yzf.smsforward.utils.IPUtils.outNetIp)) {
            return com.yzf.smsforward.utils.IPUtils.outNetIp;
        }
        Request request = new Request.Builder().url("http://pv.sohu.com/cityjson").get().build();
        try {
            Response response = mOkHttpClient.newCall(request).execute();
            String result = response.body().string();
            if (TextUtils.isEmpty(result)) {
                return "";
            }
            int satrtIndex = result.indexOf("{");//包含[
            int endIndex = result.indexOf("}");//包含]
            String json = result.substring(satrtIndex, endIndex + 1);//包含[satrtIndex,endIndex)
            Log.d(TAG, "json = " + json);
            JSONObject jo = null;
            try {
                jo = new JSONObject(json);
                String ip = jo.getString("cip");
                Log.d(TAG, "ip = " + ip);
                return "http://" + ip;
            } catch (JSONException e) {
                e.printStackTrace();
                return "";
            }
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
    }

    //http://zmtx.ddns.net:65060
    public static void doPost(final Context context, final JSONObject json, final String url, final  com.yzf.smsforward.utils.HttpXUtils.MyCallback myCallback) {
        Log.d(TAG, "doPost params = " + json.toString());
        Log.d(TAG, "doPost url = " + url);
        mOkHttpClient = getUnsafeOkHttpClient();

        new Thread(new Runnable() {
            @Override
            public void run() {
                com.yzf.smsforward.utils.IPUtils.outNetIp = doGetOutIp();
                RequestBody body = null;
                try {
                    body = createFromBody(json);
                } catch (JSONException e) {
                    e.printStackTrace();
//                    myCallback.onFailed("555", e.getMessage());
                }
                if (body == null) {
                    return;
                }
                String doPostUrl = com.yzf.smsforward.utils.IPUtils.getOutNetIP(context) + url;
                Log.d(TAG, "doPost doPostUrl = " + doPostUrl);
                Request request = null;
                Log.d(TAG, "HttpUtils request isLogin = " + LoginManager.isLogin);
                if (LoginManager.isLogin) {
                    try {
                        request = new Request.Builder().url(doPostUrl).post(body).build();
                    } catch (Exception e) {
                        e.printStackTrace();
                        com.yzf.smsforward.utils.Utils.delFromSP(context, Constants.HTTPS_URL, Constants.HTTPS_URL_KEY);
                        System.exit(-1);
                    }
                } else {
                    Log.d(TAG, "sessionID = " + sessionID);
                    //                    if(isTest){
                    //                        sessionID = "JSESSIONID=D153314FC8246C355200312DCAC37C51";
                    //                    }
                    request = new Request.Builder().url(doPostUrl).addHeader("cookie", sessionID).post(body).build();
                    isTest = false;
                }
                mOkHttpClient.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Log.d(TAG, " HttpUtils doPos failed");
//                        callback.onFailed(Constants.HTTP_ERROR + "", Constants.HTTP_DOPOST_FAILED);
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Call call, Response response) {
                        if (response.isSuccessful()) {
                            Log.d(TAG, " HttpUtils doPos success response = " + response.toString());
                            JSONObject respJson = responseToJson(response);
                            Log.d(TAG, " HttpUtils doPos respJson = " + respJson);

                            Headers headers = response.headers();
                            List cookies = headers.values("Set-Cookie");
                            if (cookies.size() > 0) {
                                String session = (String) cookies.get(0);
                                sessionID = session.substring(0, session.indexOf(";"));
                                Log.d(TAG, "sessionID = " + sessionID + "-----------isLogin = " + LoginManager.isLogin);
                            }


                            try {
                                String respCode = respJson.get(Constants.RESP_CODE) + "";
                                if (respCode.equals(Constants.SUCCESS)) {
//                                    callback.onSuccess(respJson.toString());
                                } else {
//                                    callback.onFailed(respJson.get(Constants.RESP_CODE) + "", respJson.getString(Constants
//                                            .RESP_MESSAGE));
                                }
                            } catch (JSONException e) {
//                                callback.onFailed(response.code() + "", response.message());
                                e.printStackTrace();
                            }

                        } else {
                            Log.d(TAG, " HttpUtils doPos failed response " + response.code() + " " + response.toString());
//                            callback.onFailed(response.code() + "", response.message());
                        }
                    }
                });
            }
        }).start();
    }

    private static FormBody createFromBody(JSONObject json) throws JSONException {
        Log.d(TAG, "createFromBody JSON = " + json);
        FormBody.Builder formBuilder = new FormBody.Builder();
        JSONArray names = json.names();
        for (int i = 0; i < names.length(); i++) {
            String name = names.getString(i);
            String value = json.getString(name);
            formBuilder.add(name, value);
        }
        return formBuilder.build();
    }

    private static JSONObject responseToJson(Response response) {
        JSONObject json = new JSONObject();
        Log.d(TAG, "httpUtils responseToJson resp = " + response.toString());
        try {
            String responseStr = response.body().string();
            json = new JSONObject(responseStr);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return json;
    }

    //okHttp3添加信任所有证书

    public static OkHttpClient getUnsafeOkHttpClient() {

        try {
            final TrustManager[] trustAllCerts = new TrustManager[]{
                    new X509TrustManager() {
                        @Override
                        public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) {
                        }

                        @Override
                        public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) {
                        }

                        @Override
                        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                            return new java.security.cert.X509Certificate[]{};
                        }
                    }
            };

            final SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
            final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
            OkHttpClient.Builder builder = new OkHttpClient.Builder();
            builder.sslSocketFactory(sslSocketFactory);

            builder.hostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });

            return builder.build();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }


}
